package com.funong.matrix.biz.massage.domain;

import com.funong.matrix.biz.base.entity.SysMsgBusinessTemplateEntity;
import com.funong.matrix.biz.base.entity.SysSendTaskEntity;
import com.funong.matrix.biz.massage.facade.MessageBuildStrategyContext;
import com.funong.matrix.biz.massage.facade.MessageSendStrategyContext;
import com.funong.matrix.biz.massage.pojo.BusinessTemplateDTO;
import com.funong.matrix.biz.massage.pojo.MessageInfoDTO;
import com.funong.matrix.biz.massage.pojo.SendMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class MsgDomainDao {

    @Resource
    private SysInmailDomainDao inmailDao;

    @Resource
    private SysSendTaskDomainDao sendTaskDao;

    @Resource
    private SysMsgTemplateDomainDao templateDao;

    @Resource
    private SysMsgBusinessTemplateDomainDao businessTemplateDao;

    @Resource
    private MessageSendStrategyContext messageSender;
    @Resource
    private MessageBuildStrategyContext messageBuilder;

    public String sendMessage(MessageInfoDTO messageInfoDTO){
        StringBuilder sbSendResult = new StringBuilder();

        List<SysMsgBusinessTemplateEntity> businessTemplateList = businessTemplateDao.findTemplateByCode(messageInfoDTO.getBusinessCode());

        List<BusinessTemplateDTO> businessTemplateDTOS = templateDao.findTemplateDTO(businessTemplateList);

        for (BusinessTemplateDTO businessTemplateDTO : businessTemplateDTOS) {
            String messageType = businessTemplateDTO.getMessageType();

            SendMessageDTO sendMessageDTO = messageBuilder.buildMessageContent(messageType, messageInfoDTO, businessTemplateDTO);

            SysSendTaskEntity sendTaskEntity = sendTaskDao.recordTask(sendMessageDTO, businessTemplateDTO);

            String sendResult = messageSender.sendMessage(sendMessageDTO, businessTemplateDTO, sendTaskEntity);

            sbSendResult.append(sendResult).append(";");
        }
        return sbSendResult.toString();
    }
}
